package com.quanxi.qxaimain.service.IndexDebuggingServer;


import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.quanxi.qxaimain.common.globalException.NotControllerResponseAdvice;
import com.quanxi.qxaimain.dao.IndexDebugging.IndexDebuggingMapper;
import jdk.nashorn.internal.objects.NativeString;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static java.lang.System.out;

/**
 * Author: caiyisen
 * Date: 2024/7/17
 * Time: 14:54
 * Package:com.quanxi.qxaimain.service.IndexDebugging
 * Project:qxaimain
 */
@Service("IndexDebuggingServer")
public class IndexDebuggingServerImpl implements IndexDebuggingServer {
    @Resource
    private IndexDebuggingMapper Mapper;

    @Override
    @NotControllerResponseAdvice
    public JSONObject AddSqlNew(JSONObject params) {
        try {
            String ind_id = params.getString("ind_id");
            String ind_name = params.getString("ind_name");
            String ind_def = params.getString("ind_def");
            String sql_total = params.getString("sql_total");
            int total_flag = params.getInteger("total_flag");
            int is_detail = params.getInteger("is_detail");
            String sql_detail = params.getString("sql_detail");
            int detail_flag = params.getInteger("detail_flag");
            int source = params.getInteger("source");
            String dept_name = params.getString("dept_name");
            String model_name = params.getString("model_name");
            String sql_value = params.getString("sql_value");
            String sql_detail_value = params.getString("sql_detail_value");
            String sql_time = params.getString("sql_time");
            String sql_detail_time = params.getString("sql_detail_time");
            String admin_name = params.getString("admin_name");
            String table_name = params.getString("table");/*当前日期和时间: 2024-07-12T18:18:53.630 格式化后的日期和时间: 2024-07-12 18:18:53*/

//            LocalDateTime currentDateTime = LocalDateTime.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            String formattedDateTime = currentDateTime.format(formatter);

            int maps = Mapper.sql_AddSqlNew(ind_id, ind_name, ind_def, sql_total, total_flag,
                    is_detail, sql_detail, detail_flag, source, dept_name, model_name, sql_value,
                    sql_detail_value, sql_time, sql_detail_time, admin_name, table_name);
            out.println(maps);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "add success");
            return jsonObject;
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("msg", "add error");


            return jsonObject;

        }

    }

    @Override
    @NotControllerResponseAdvice
    public Object Delete(JSONObject params) {
        try {
            int id = params.getInteger("id");
            String admin_name = params.getString("admin_name");
            String table_name = params.getString("table");
            int maps = Mapper.sql_Delete(id, admin_name, table_name);
            out.println(maps);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "delete success");


            return jsonObject;
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("msg", "delete error");


            return jsonObject;

        }
    }

    @Override
    @NotControllerResponseAdvice
    public Object UpdateSqlNew(JSONObject params) {
        try {
            int id = params.getInteger("id");
            String ind_id = params.getString("ind_id");
            String ind_name = params.getString("ind_name");
            String ind_def = params.getString("ind_def");
            String sql_total = params.getString("sql_total");
            int total_flag = params.getInteger("total_flag");
            int is_detail = params.getInteger("is_detail");
            String sql_detail = params.getString("sql_detail");
            int detail_flag = params.getInteger("detail_flag");
            int source = params.getInteger("source");
            String dept_name = params.getString("dept_name");
            String model_name = params.getString("model_name");
            String sql_value = params.getString("sql_value");
            String sql_detail_value = params.getString("sql_detail_value");
            String sql_time = params.getString("sql_time");
            String sql_detail_time = params.getString("sql_detail_time");
            String admin_name = params.getString("admin_name");
            String table_name = params.getString("table");
            int maps = Mapper.sql_UpdateSqlNew(id, ind_id, ind_name, ind_def, sql_total, total_flag,
                    is_detail, sql_detail, detail_flag, source, dept_name, model_name, sql_value,
                    sql_detail_value, sql_time, sql_detail_time, admin_name, table_name);

            out.println(maps);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "update success");


            return jsonObject;
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("msg", "update error");


            return jsonObject;

        }
    }

    @Override
    @NotControllerResponseAdvice
    public Object Search(JSONObject params) {
        try {
            Integer sortFlag = params.getInteger("sortFlag"); //获取参数

            //获取参数，确定按什么方式排序
            String px_time = (sortFlag == null) ? "update_time" : (sortFlag == 0) ? "CAST(REPLACE(sql_time, 'ms', '') AS SIGNED)" : (sortFlag == 1) ? "CAST(REPLACE(sql_detail_time, 'ms', '') AS SIGNED)" : "update_time"; //根据获取参数类型决定用什么字段排序

            String table_name = params.getString("table");//获取表名

            List sb = params.getJSONArray("indIdArr");//获取字段
            //转化为字符串，去除[]括号，好方便SQL in（，，）
            String ind_id_arr = (params.getJSONArray("indIdArr") == null) ? null : sb.toString().replaceAll("\\[|]", "");

            String keyWord = params.getString("keyWord"); //获取搜索参数
            String monthPeriod = params.getString("monthPeriod");//获取时间区间

            String str1 = NativeString.substring(monthPeriod, 8, 15);//获取开始时间
            String str2 = NativeString.substring(monthPeriod, 0, 7);//获取结束时间

            List<Map<String, Object>> maps = Mapper.sql_Search(keyWord, table_name, px_time, ind_id_arr, monthPeriod);//获取qxzsk库数据

            List<Map<String, String>> maps1 = Mapper.sql_Search1(monthPeriod);//调用函数获取应用层数据

            List<Map<String, String>> maps2_1 = Mapper.sql_Search2_1(monthPeriod, str1, str2);//调用函数获取应用层数据 kpi_quota
            List<Map<String, String>> maps2_2 = Mapper.sql_Search2_2(monthPeriod, str1, str2);//调用函数获取dm层数据 kpi_key_quota
            List<Map<String, String>> maps2_3 = Mapper.sql_Search2_3(monthPeriod, str1, str2);//调用函数获取dm层数据 kpi_third_quot


            int countPage = maps.size();//计算总数，用于分页计算

            List<Map<String, Object>> data = new ArrayList<>();//按规定格式获取qxzsk数据
            List<Map<String, Object>> failureDataList = new ArrayList<>();//按规定格式获取错误数据
            List<Map<String, Object>> noDMDataList = new ArrayList<>();//按规定格式获取dm层数据


            Map<String, Object> noAppDataList = new LinkedHashMap<>();//按规定格式获取应用层数据
            List<Object> kpi_quota = new ArrayList<>(); //应用层数据 kpi_quota
            List<Object> kpi_key_quota = new ArrayList<>(); //应用层数据 kpi_key_quota
            List<Object> kpi_third_quot = new ArrayList<>(); //应用层数据 kpi_third_quot


            //计算判断dw层数据和dm,应用层数据匹配
            for (Map<String, Object> map : maps) {

                Map<String, Object> noDMData = new HashMap<>();//dm层数据对象
                Map<String, Object> failureData = new HashMap<>();//错误数据对象
                Map<String, Object> noAppData = new HashMap<>();//应用层数据对象

                String[] list = {null, null, null};//初始化列表用于存放应用层3个表中数据，顺序存放

                map.put("application_db_value", list);//为map对象中application_db_value数据初始为空，
                String ind_id = map.get("ind_id").toString();//获取编码

                String ind_name = map.get("ind_name").toString();//获取编码name

                String admin_name = map.get("admin_name").toString();//获取name

                String status = (map.get("status") == null) ? null : map.get("status").toString();//get获取为空会报错

                //判断是否为错误的条件
                if (map.get("sql_detail_value") != null || map.get("sql_detail") != null || map.get("sql_value") != null) {
                    if (map.get("sql_value").toString().contains("失败") || map.get("sql_value").toString().contains("未调试") || map.get("sql_detail_value").toString().contains("失败") || map.get("sql_detail_value").toString().contains("未调试") || (map.get("sql_detail_value").toString().contains("sql成功") == false && map.get("sql_detail").toString().equals("") == true)) {
                        //添加规定的对象数据
                        failureData.put("ind_id", ind_id);//添加规定的对象数据
                        failureData.put("ind_name", ind_name);
                        failureData.put("admin_name", admin_name);
                        failureData.put("status", status);
                        failureDataList.add(failureData);
                    }
                }

                //循环dm层数据找到合适数据匹配qxzsk数据
                for (Map<String, String> map1 : maps1) {
                    if (map1.get("IND_ID").equals(ind_id)) {
                        if (map1.get("BACKEND_VALUE") != null && map1.get("BACKEND_VALUE").equals("") == false) {
                            map.put("backend_value", map1.get("BACKEND_VALUE"));//添加dm层数据
                            break;
                        }

                    }
                }

                //未匹配上的数据存入
                if (map.get("backend_value").equals("")) {
                    noDMData.put("ind_id", ind_id);
                    noDMData.put("ind_name", ind_name);
                    noDMData.put("admin_name", admin_name);
                    noDMData.put("status", status);
                    noDMDataList.add(noDMData);
                }


                //获取应用层表数据，并做判断出错误数据和正确数据分组存入
                for (Map<String, String> map2_1 : maps2_1) {
                    if (map2_1.get("ind_id").equals(ind_id)) {
                        if ((map2_1.get("kpi_quota") != null && map2_1.get("kpi_quota").equals("") == false)) {
                            list[0] = (map2_1.get("kpi_quota").equals("") == false) ? map2_1.get("kpi_quota") : null;
                            break;
                        }
                    }
                }

                for (Map<String, String> map2_2 : maps2_2) {
                    if (map2_2.get("ind_id").equals(ind_id)) {
                        if ((map2_2.get("kpi_key_quota") != null && map2_2.get("kpi_key_quota").equals("") == false)) {
                            list[1] = (map2_2.get("kpi_key_quota").equals("") == false) ? map2_2.get("kpi_key_quota") : null;
                            break;
                        }
                    }
                }

                for (Map<String, String> map2_3 : maps2_3) {
                    if (map2_3.get("ind_id").equals(ind_id)) {
                        if ((map2_3.get("kpi_third_quot") != null && map2_3.get("kpi_third_quot").equals("") == false)) {
                            list[2] = (map2_3.get("kpi_third_quot").equals("") == false) ? map2_3.get("kpi_third_quot") : null;
                            break;
                        }
                    }
                }


                noAppData.put("ind_id", ind_id);
                noAppData.put("ind_name", ind_name);
                noAppData.put("admin_name", admin_name);
                noAppData.put("status", status);
                if (list[0] == null)
                {
                    kpi_quota.add(noAppData);
                }
                if (list[1] == null)
                {
                    kpi_key_quota.add(noAppData);
                }
                if (list[2] == null){
                    kpi_third_quot.add(noAppData);
                }

                map.put("application_db_value", list);//添加dm层数据
                data.add(map);
            }
            noAppDataList.put("kpi_quota", kpi_quota);
            noAppDataList.put("kpi_key_quota", kpi_key_quota);
            noAppDataList.put("kpi_third_quot", kpi_third_quot);

            //分页的参数输入
            int pageNum = params.getInteger("pageNum");
            int pageSize = params.getInteger("pageSize");
//            PageHelper.startPage(pageNum, pageSize);//分页
            //集合的分页函数
            List<Map<String, Object>> data1 = ListUtil.page(pageNum - 1, pageSize, data);


            JSONObject jsonObject = new JSONObject();
            //设计返回参数
            jsonObject.put("code", 1);
            jsonObject.put("countPage", countPage);
            jsonObject.put("data", data1);
            jsonObject.put("msg", "success");
            jsonObject.put("failureDataList", failureDataList);
            jsonObject.put("noAppDataList", noAppDataList);
            jsonObject.put("noDMDataList", noDMDataList);
            return jsonObject;

        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("data", null);
            jsonObject.put("msg", "error");


            return jsonObject;

        }

    }

    @Override
    @NotControllerResponseAdvice
    public Object Download(JSONObject params) {
        try {
            Integer sortFlag = params.getInteger("sortFlag"); //获取参数

            String px_time; //根据获取参数类型决定用什么字段排序
            if (sortFlag == null) { //根据获取参数类型决定用什么字段排序
                px_time = "update_time";
            } else if (sortFlag == 0) {
                px_time = "CAST(REPLACE(sql_time, 'ms', '') AS SIGNED)";
            } else if (sortFlag == 1) {
                px_time = "CAST(REPLACE(sql_detail_time, 'ms', '') AS SIGNED)";
            } else {
                px_time = "update_time";
            }
            String table_name = params.getString("table");//获取表名
            List sb = params.getJSONArray("indIdArr");//获取字段
            String ind_id_arr;
            if (sb == null) {
                ind_id_arr = null;
            } else {
                ind_id_arr = sb.toString().replaceAll("\\[|]", "");
            }

            String keyWord = params.getString("keyWord");
            String monthPeriod = params.getString("monthPeriod");

            String str1 = NativeString.substring(monthPeriod, 8, 15);//获取开始时间
            String str2 = NativeString.substring(monthPeriod, 0, 7);//获取结束时间

            List<Map<String, Object>> maps = Mapper.sql_Search(keyWord, table_name, px_time, ind_id_arr, monthPeriod);

            List<Map<String, String>> maps1 = Mapper.sql_Search1(monthPeriod);//调用函数获取dw层数据

            List<Map<String, String>> maps2_1 = Mapper.sql_Search2_1(monthPeriod, str1, str2);//调用函数获取应用层数据 kpi_quota
            List<Map<String, String>> maps2_2 = Mapper.sql_Search2_2(monthPeriod, str1, str2);//调用函数获取dm层数据 kpi_key_quota
            List<Map<String, String>> maps2_3 = Mapper.sql_Search2_3(monthPeriod, str1, str2);//调用函数获取dm层数据 kpi_third_quot


            List<Map<String, Object>> data = new ArrayList<>();


            for (Map<String, Object> map : maps) {
                String[] list = {null, null, null};
                String ind_id = map.get("ind_id").toString();//获取编码
                for (Map<String, String> map1 : maps1) {
                    if (map1.get("IND_ID").equals(ind_id)) {
                        if (map1.get("BACKEND_VALUE") != null && map1.get("BACKEND_VALUE").equals("") == false) {
                            map.put("backend_value", map1.get("BACKEND_VALUE"));//添加dm层数据
                            break;
                        }

                    }
                }

                for (Map<String, String> map2_1 : maps2_1) {
                    if (map2_1.get("ind_id").equals(ind_id)) {
                        if ((map2_1.get("kpi_quota") != null && map2_1.get("kpi_quota").equals("") == false)) {
                            list[0] = (map2_1.get("kpi_quota").equals("") == false) ? map2_1.get("kpi_quota") : null;
                            break;
                        }
                    }
                }

                for (Map<String, String> map2_2 : maps2_2) {
                    if (map2_2.get("ind_id").equals(ind_id)) {
                        if ((map2_2.get("kpi_key_quota") != null && map2_2.get("kpi_key_quota").equals("") == false)) {
                            list[1] = (map2_2.get("kpi_key_quota").equals("") == false) ? map2_2.get("kpi_key_quota") : null;
                            break;
                        }
                    }
                }

                for (Map<String, String> map2_3 : maps2_3) {
                    if (map2_3.get("ind_id").equals(ind_id)) {
                        if ((map2_3.get("kpi_third_quot") != null && map2_3.get("kpi_third_quot").equals("") == false)) {
                            list[2] = (map2_3.get("kpi_third_quot").equals("") == false) ? map2_3.get("kpi_third_quot") : null;
                            break;
                        }
                    }
                }

                map.put("application_db_value", list);//添加dm层数据
                data.add(map);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 1);
            jsonObject.put("data", data);
            jsonObject.put("msg", "success");


            return jsonObject;

        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 0);
            jsonObject.put("data", null);
            jsonObject.put("msg", "error");


            return jsonObject;

        }
    }
}
